<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>PCM Stream Player</title>
</head>

<body>
<div style="width: 800px ;margin: auto">
    <textarea id="inputs"  style="width: 100%;height: 100px"> hell world</textarea>
    <br>
    <textarea id="output" style="width:100%;height: 300px;"></textarea>
    <br>
    <button onclick="startStream()">提交</button>
</div>


<script src="./js/pcmPlayer.js"></script>
<script>
    async function startStream() {
        let url = 'http://127.0.0.1:8081/sse/mitter/stream-sse-sink-tts'
        const message = document.getElementById("inputs").value;
        const response = await fetch(url, {
            method: 'POST',
            headers: {"Content-Type": "application/json"},
            body: message
        });

        var player = new PCMPlayer({
            encoding: "16bitInt",
            channels: 1,
            sampleRate: 22050,
            flushingTime: 180
        });


        const reader = response.body.getReader();

        let out = document.getElementById("output");
        let tempResult = ''
        let text = ''
        while (true) {
            const {done, value} = await reader.read();
            if (done) {
                console.log("done",out,text)
                break;
            }
            const decoder = new TextDecoder('utf-8')
            let str = decoder.decode(value, {stream: true})
            tempResult += str
            const split = tempResult.match(/data:.*}\n\n/g)

            if (split) {
                str = split.join('')
                tempResult = tempResult.replace(str, '')
            }

            if (str && str.startsWith('data:')) {
                if (split) {
                    for (const index in split) {
                        const chunk = JSON?.parse(split[index].replace('data:', ''))

                        console.log(chunk)
                        if (chunk.text!==""){
                            text += chunk.text
                            out.value = text;
                        }else{
                            let uint8Array = Uint8Array.from(atob(chunk.audio), (c) => c.charCodeAt(0));
                            // console.log("test",chunk,uint8Array)
                            player.feed(uint8Array);
                        }
                    }
                }
            }

        }
    }
</script>
</body>

</html>
